"use client";

import React, { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import "./globals.css";

export default function Cursor ()  {
  const cursorRef = useRef<HTMLDivElement>(null);
  const [cursorStyle, setCursorStyle] = useState<'small' | 'large'>('small');

  useEffect(() => {
    const cursorElement = cursorRef.current;
    if(!cursorElement) return;
    const moveCursor = (e: MouseEvent) => {
      if (cursorElement) {
        gsap.to(cursorElement, {
          duration: 0.2,
          left: `${e.clientX}px`,
          top: `${e.clientY}px`,
          ease: "power1.out"
        });
      }
    };
    const zoomCursor = () => {
      if (cursorElement) {
        gsap.to(cursorElement, {
          duration: 0.1,
          scale: 3,
          ease: "power1.out"
        });
        setCursorStyle('large');
      }
    };
    const closeCursor = () => {
      if (cursorElement) {
        gsap.to(cursorElement, {
          duration: 0.1,
          scale: 3,
          ease: "power1.out"
        });
        setCursorStyle('large');
      }
    };
    const defaultCursor = () => {
      if (cursorElement) {
        gsap.to(cursorElement, {
          duration: 0.1,
          scale: 1,
          ease: "power1.out"
        });
        setCursorStyle('small');
      }
    };
    window.addEventListener("mousemove", moveCursor);
    document.querySelectorAll("a, button, .zoom-cursor").forEach(el => {
      el.addEventListener("mouseenter", zoomCursor);
    });
    document.querySelectorAll(".trigger-close").forEach(el => {
      el.addEventListener("mouseenter", closeCursor);
    });
    document.querySelectorAll("a, button, .zoom-cursor, .trigger-close, .trigger-plus").forEach(el => {
      el.addEventListener("mouseleave", defaultCursor);
    });
    return () => {
      window.removeEventListener("mousemove", moveCursor);
      document.querySelectorAll("a, button, .zoom-cursor").forEach(el => {
        el.removeEventListener("mouseenter", zoomCursor);
      });
      document.querySelectorAll(".trigger-close").forEach(el => {
        el.removeEventListener("mouseenter", closeCursor);
      });
      document.querySelectorAll("a, button, .zoom-cursor, .trigger-close, .trigger-plus").forEach(el => {
        el.removeEventListener("mouseleave", defaultCursor);
      });
    };
  }, [cursorRef]);

  return (
    <div ref={cursorRef} className={`cursor ${cursorStyle}`}></div>
  );
};

